#!/bin/bash

# Change these to reflect your setup
SIMICS_DIR=/work/simics
X86_64_DIR=/opt/x86-64


# Do not set this flag to anything. It is being set by the different passes
CFLAGS=


# Run a test
function runtest() {
  echo -e "run\ncpu0.pregs\nquit" | \
    ./simics -x abitest.runtime >/tmp/simics.out 2>/dev/null

  if [ "`grep eeeeeeee /tmp/simics.out`" == "" ] ; then
    echo "*** Fail! ***"
  else
    echo "Ok."
  fi
}

# Build the new test
function build() {
  rm -f a.out
  rm -f /tmp/test.o
  rm -f /tmp/image.simics

  x86_64-unknown-linux-gcc -I /usr/include -c $* $CFLAGS -o /tmp/test.o -DSTACK_SIZE=1024
  x86_64-unknown-linux-ld -T $X86_64_DIR/lib/ldscr2.lds $X86_64_DIR/lib/start64.o $X86_64_DIR/lib/libc.a /tmp/test.o $X86_64_DIR/lib/libc.a -o a.out
  x86_64-unknown-linux-ld -T $X86_64_DIR/lib/ldscr.lds a.out -o /tmp/image.simics
}

# Test a file
function test_file() {
  echo -n "$1: "
  if [ "$CFLAGS" != "" ] && [ "`grep 'optimization level' $1 | grep -e $CFLAGS`" != "" ] ; then
    echo "Skipped."
  else
    build $*
    if [ -f /tmp/image.simics ] ; then
      pushd $SIMICS_DIR/home/x86-test-machine >/dev/null
      runtest
      popd >/dev/null
      return
    else
      echo "Compile error"
    fi
  fi
}

function run_all_tests() {
  if [ "$CFLAGS" == "" ] ; then
    echo -e "\nTesting without optimization"
  else
    echo -e "\nTesting with $CFLAGS"
  fi

  # Testing only some files or all of them?
  if [ "$1" != "" ] ; then
    for file in $*; do
      test_file $file
    done
  else
    for file in test_*.c; do
      test_file $file;
    done
  fi
}


echo "Running make to build all autogenerated tests"
make

run_all_tests $*

CFLAGS=-O1
run_all_tests $*

CFLAGS=-O2
run_all_tests $*
